<template>
    <div class="common-layout">
      <el-container>
        <el-header class="px-50px h-98px pt-10px">
          <div class="flex justify-between">
            <div class="flex items-center">
              <div class="flex text-dark-500 self-center">
                <div class="self-center"><el-image class="w-120px h-60px mt-14px" src="/images/login-ico.png" /></div>
                <div class="self-center text-24px ml-10px mr-30px">智社考</div>
              </div>
              <div class="flex self-center mainMenu">
                <block v-for="(item,index) in menuList">
                  <router-link :to="item.path" class="text-16px font-weight-600 self-center px-20px py-10px ml-10px whitespace-nowrap" >{{ item.name }}</router-link>
                </block>
                
                  <!-- <div class="ml-10px text-16px font-weight-600 rounded-full linkText  " :class="currentTab==item.tab?'bg-red-500 text-white':''" @click="toggleTab(item.tab)">{{ item.name }}</div> -->
  
              </div>
              <div class="flex self-center mb-15px ml-10px">
                <router-link to="/ai"><el-image src="/images/deepseekr1.png" class="w-200px mt-20px mr-10px" /></router-link>
              </div>
            </div>

            <div class="flex self-center">
              <div class="flex self-center">
                <div class="self-center text-16px ml-10px mr-10px text-center text-gray-600">
                  
                  <el-dropdown ref="dropdownBook" style="margin-right: 30px">
                    <div>
                      <div @click="showDropDownBook"><el-icon :size="25"><Notebook /></el-icon></div>
                      <div class="whitespace-nowrap">科目</div>
                    </div>
                    
                      <template #dropdown>
                        <el-dropdown-menu>
                          <block v-for="(item,index) in lessonList">
                            <el-dropdown-item :class="lessonData.name == item.book_name?'text-red-500':''" @click="lessonConfirm(item)">{{ item.book_name }}</el-dropdown-item>
                          </block>
                          
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    
                </div>
                <div class="self-center text-16px ml-10px mr-10px text-center text-gray-600">
                    
                    <el-dropdown ref="dropdownMessage" trigger="contextmenu" style="margin-right: 30px">
                    <div>
                      <div><el-icon :size="25"><Bell /></el-icon></div>
                      <div class="whitespace-nowrap">消息</div>
                    </div>
                    <template #dropdown>
                        
                    </template>
                    </el-dropdown>
                    
                </div>
                <div class="flex self-center text-16px ml-10px mr-10px">
                    <div class="self-center mr-10px"><el-image class="rounded-full w-30px h-30px" :src="userInfo.avatar" fit="cover" /></div>
                    <div class="self-center">
                      <el-dropdown ref="dropdownMy" style="margin-right: 30px">
                        <div class="flex">
                          <div class="self-center mr-3px">
                            {{ userInfo.nickname }}
                          </div>
                          <div class="self-center">
                            <el-icon><ArrowDown /></el-icon>
                          </div>
                        </div>
                        
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item v-for="(item,index) in myMenuList">
                                <router-link :to="item.path" >{{ item.name }}</router-link></el-dropdown-item>
                              
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                        
                    </div>
                </div>
                <div class="self-center text-14px ml-10px mr-30px linkText" @click="doLogout">退出登录</div>
              </div>
            </div>
          </div>
        </el-header>
        <el-main  class=" bg-gray-100">
            <router-view />
        </el-main>
        <el-footer>
          <div class="leading-100px text-gray-500 text-center h-97px">浙江嘉兴康宁微信息科技有限公司 版权所有</div>
        </el-footer>
      </el-container>

      <el-dialog v-model="dialogLesson" title="请选择缴费科目" align-center :show-close="true" :close-on-press-escape="false" :close-on-click-modal="false" width="600">
        <div class="p-10px text-gray-300">
            <div class="">
              <el-radio-group v-model="orderData.type" size="large">
                <el-radio-button v-for="(item,index) in sellTypeList" :label="item" :value="item" @change="countTotalPrice()" />
              </el-radio-group>
            </div>
            <div class=" mt-20px mb-20px">
              <el-checkbox-group v-model="orderData.book" @change="countTotalPrice()">
                <block v-for="(item,index) in sellBookList">
                  <el-checkbox :value="item.book_id" class="mb-10px w-548px" border size="large" >
                    <div class="flex justify-between items-center px-10px w-510px rounded-5px">
                      <div class="mr-10px ">{{item.book_name}}</div>
                      <div class="text-gray-300" v-if="orderData.type == sellTypeList[0]">￥{{ item.book_price }}</div>
                      <div class="text-gray-300" v-else>￥{{ item.book_price2 }}</div>
                    </div>
                  </el-checkbox>
                    <!-- <div class="flex justify-between items-center border px-10px mt-10px rounded-5px w-548px">
                      <div class="mr-10px w-300px"><el-checkbox :value="item.book_id" :label="item.book_name" size="large"  /></div>
                      <div class="" v-if="orderData.type == sellTypeList[0]">￥{{ item.book_price }}</div>
                      <div v-else>￥{{ item.book_price2 }}</div>
                    </div> -->
                </block>
              </el-checkbox-group>
              
              
            </div>
            <div>


              <el-radio-group v-model="orderData.paytype" size="large">
                <el-radio-button value="wechat" >
                  <div><el-image src="/images/wxzf.png" class="w-80px h-80px"></el-image></div>
                  <div class="text-center mt-10px">微信支付</div>
                </el-radio-button>
                <el-radio-button value="alipay" >
                  <div><el-image src="/images/zfbzf.png" class="w-80px h-80px"></el-image></div>
                  <div class="text-center mt-10px">支付宝支付</div>
                </el-radio-button>
              </el-radio-group>

            </div>

            

            <div class="flex justify-end items-end">
              <div class="text-dark-500">总计缴费金额：</div>
              <div class="text-24px text-red-500 font-600">￥{{orderData.totalPrice}}</div>
            </div>
            
            <div class="flex mt-20px mb-20px">
                <el-button type="primary" class="w-full" @click="submitOrder()">提交订单</el-button>
            </div>
            
        </div>
      </el-dialog>

      <el-dialog v-model="dialogPay" title="扫码支付" align-center :show-close="true" @close="closePayDialog()" :close-on-press-escape="false" :close-on-click-modal="false" width="600">
        <div class="text-center">
              <vue-qrcode
                :value="codeUrl"
                :options="{
                  width: 256,
                  errorCorrectionLevel: 'H'
                }"
              ></vue-qrcode>
            </div>
            <div class="text-center text-24px mb-20px"><el-countdown title="" :value-style="{'color':'#fc5751','text-align':'center'}" :value="cutdownTime" @finish="onFinish" /></div>
            <div class="text-center text-24px mb-20px">请使用{{ orderData.paytype == 'wechat' ? '微信' : '支付宝'}}扫码支付</div>
            
      </el-dialog>

      <div class="absolute left-10px top-300px linkText" @click="dialogLesson = true">
        <el-image src="/images/buy.jpg" class="w-200px h-113px"></el-image>
      </div>

    </div>
  </template>
  <script setup>
    import { useUserStore } from '../stores/user'
    import { configStore } from '../stores/config'
    import { httpApi,userApi,systemApi } from '../api/api'
    import { ElMessage,ElMessageBox } from 'element-plus'
    import { ref,onMounted, nextTick  } from "vue"
    import { useRouter } from 'vue-router'
    import QRCode from 'qrcode' // 导入二维码库

    const dialogLesson = ref(false)
    const dialogPay = ref(false)
   
    const sellTypeList = ref([])
    const orderData = ref({
      paytype:"wechat",
      totalPrice:0,
    })
    const cutdownTime = ref(Date.now() + 1000 * 60 * 5)
    const codeUrl = ref("weixin://wxpay/bizpayurl?pr=KPUReb3z1")
    const orderid = ref("") //订单ID
    
    
    const router = useRouter()
  
    const menuList = ref([
      {name:"首页",exact:1,path:"/home"},
      {name:"智能计划",exact:0,path:"/plan"},
      {name:"智能题库",exact:0,path:"/exam"},
      {name:"智能教材",exact:0,path:"/book"},
      {name:"智能互动",exact:0,path:"/interaction"},
      // {name:"智能答疑",exact:0,path:"/answer"},
      {name:"AI智能体",exact:0,path:"/ai"},
      
    ])

    const myMenuList = ref([
      // {name:"个人资料",tab:1,path:"/"},
      // {name:"学习进度",tab:2,path:"/book"},
      // {name:"智能计划",tab:3,path:"/plan/todayPlan"},
      // {name:"我的笔记",tab:4,path:"/my"},
      // {name:"我的收藏",tab:5,path:"/my"},
      // {name:"我的错题",tab:6,path:"/my"},
      // {name:"我的贴子",tab:7,path:"/my"},
      // {name:"学习情况",tab:7,path:"/my"},
    ])

    const bookList = ref([]);

    let currentTab = ref(1)

    const userStore = useUserStore()
    const userInfo = userStore.getUserInfo()
    const config= configStore()
  
    const toggleTab = (tabValue)=>{
      currentTab.value = tabValue
      
    }
    const dropdownBook = ref(null)
    const showDropDownBook = ()=>{
      if (!dropdownBook.value) return
      dropdownBook.value.handleOpen()
    }

    let lessonList = ref([])
    let lessonData = ref({})

    const configInit = async()=>{
        const res = await systemApi.getConfig()
        if(res.code){
          config.setConfig(res.data)
        }
        //console.log("configData",res)
    }

    

    const init=async()=>{
      configInit()

      let res = await httpApi.getLessons()
      if(res.code){
        lessonList.value= []
        res.data.map(item=>{
          lessonList.value.push(item)
        })

        getBookList() //获取售卖课程列表

        if(lessonList.value.length == 0){
          dialogLesson.value = true
        }
        lessonData.value.name = lessonList.value[0].book_name
        lessonData.value.image = lessonList.value[0].image
        lessonData.value.book_id = lessonList.value[0].book_id
        lessonData.value.chat_id = lessonList.value[0].chat_id
				config.setBook(lessonData.value)
        //console.log("课程数据",lessonData.value)
      }
    }

    const sellBookList = ref([]) //课程列表 ，前端售卖的
    const getBookList = async()=>{
      let res = await httpApi.sellLessons()
      if(res.code){
        //console.log("售卖课程",res.data.books)
        //console.log("已买课程",lessonList.value)
        sellBookList.value= filterArrayB(lessonList.value,res.data.books)
        //console.log("售卖课程2",sellBookList.value)
        sellTypeList.value = res.data.types
        orderData.value.type = sellTypeList.value[0]
        //console.log("销售列表",sellBookList.value)
      }
    }

    const filterArrayB = (arrayA, arrayB)=>{ //去除售卖列表中已经购买的课程
      const aIds = new Set(arrayA.map(item => item.book_id));
      return arrayB.filter(item => !aIds.has(item.book_id));
    }

    const countTotalPrice = async()=>{
      
      let totalPrice = 0
      
      sellBookList.value.map(item=>{
        orderData.value.book.map(book=>{
          if(book == item.book_id){
            
            if(orderData.value.type == sellTypeList.value[0]){
              
              totalPrice += item.book_price
            }else{
              totalPrice += item.book_price2
            }
          }
        })
      })
      
      orderData.value.totalPrice = totalPrice
      //await nextTick()
    }

    const submitOrder = async()=>{
      if(orderData.value.totalPrice == 0){
        ElMessage({
          message: "请选择科目",
          type: 'warning',
        })
        return
      }
      let params ={}
      let note = [] //备注
      params.book_id = orderData.value.book.join(",")
      orderData.value.book.map(book=>{
        sellBookList.value.map(item=>{
          if(book == item.book_id){
            note.push(item.book_name)
          }
        })
      })
      params.memo = note.join(",")
      params.title = "智社考系统课程购买：" + orderData.value.type
      params.paytype = orderData.value.paytype
      params.amount = orderData.value.totalPrice
      //params.payamount = orderData.value.totalPrice //提交的时候不需要支付总金额，这个会在回调的时候填入
      //console.log("提交订单",params)
      let res = await httpApi.submitOrder(params)
      if(res.code){
        
          codeUrl.value = res.data.code_url
          //console.log("倒计时1",cutdownTime.value)
          cutdownTime.value = res.data.cutdownTime
          //console.log("倒计时2",cutdownTime.value)
          dialogPay.value = true
          orderid.value = res.data.orderid
          startPolling(orderid.value) //开始轮询
        
      }

    }

    const closePayDialog = ()=>{
      dialogPay.value = false
      clearInterval(pollingInterval.value);
    }

    const onFinish = async()=>{ //倒计时结束后设置订单过期
      dialogPay.value = false
      clearInterval(pollingInterval.value);
      let res = await httpApi.setOrderExpired({orderid:orderid.value})
      if(res.code){
        ElMessage({
          message: "订单已过期",
          type: 'warning',
        })
      }
    
    }

    const pollingInterval = ref(null);

    const startPolling = async (orderid) => {
      let retryCount = 0;
      
      const check = async () => {
        try {
          const res = await httpApi.pollingOrder({orderid:orderid});
          
          if (res.data.status === 'paid') {
            clearInterval(pollingInterval.value);
            init()  //刷新一下数据
            ElMessage({
              message: '支付成功',
              type: 'success',
            });
            dialogPay.value = false
            dialogLesson.value = false

            // 跳转到成功页面
          } 
          
          retryCount = 0; // 成功查询重置重试计数器
          
        } catch (error) {
          if (retryCount++ > 3) {
            clearInterval(pollingInterval.value);
            ElMessage({
              message: '支付失败，请重试',
              type: 'error',
            });
            dialogPay.value = false
          }
        }
      };

      // 初始立即检查
      check();
      
      // 启动轮询（渐进式间隔）
      pollingInterval.value = setInterval(() => {
        check();
      }, createBackoffInterval(retryCount));
    }
    // 指数退避算法
    const createBackoffInterval = (attempt) => {
      return Math.min(1000 * Math.pow(2, attempt), 30000); // 最大间隔30秒
    }



    const lessonConfirm = (item)=>{
      lessonData.value.name = item["book_name"]
      lessonData.value.image = item["image"]
      lessonData.value.book_id = item["book_id"]
      lessonData.value.chat_id = item["chat_id"]
				// this.chapterList = []
				// this.sectionList = []
				// this.tabIndex = 0 //重置标签项
				config.setBook(lessonData.value)
        config.setCurrentOpen({})//重置阅读章节
				//this.setPoint()
				//this.setData()
				
			}

    onMounted(()=>{
      init()
      
    })
    const doLogout = async()=>{
      ElMessageBox.confirm("确定要退出智社考系统？", '温馨提醒', {
        confirmButtonText: '确定',   // 修改确认按钮文字
        cancelButtonText: '取消',    // 修改取消按钮文字
        type: 'warning'
      }).then(async()=>{
        let res = await userApi.doLogout()
        if(res.code){
            userStore.setToken("")
            userStore.setUserInfo({})
            ElMessage({
                message: res.msg,
                type: 'success',
            })
            setTimeout(()=>{
              router.push("/auth/login")
            },1000)
            
        }else{
            ElMessage({
                message: res.msg,
                type: 'error',
            })
        }
      })
        
    }
  
  </script>
  <style scoped>
    .footer{
      /*background: url("../../../public/images/footer.png") no-repeat center center;*/
    }
    .linkText{
          cursor: pointer;
      }
      .mainMenu a.router-link-active,.mainMenu a:hover {
        color:white;
        background-color: #fc5751;
        border-radius: 100px;
        }
        
  /* 移除焦点边框 */
:deep(.el-dropdown__trigger:focus) {
  outline: none!important;
}
:deep(.el-tooltip__trigger:focus) {
  outline: none!important;
}


  </style>